/**
 * 
 */
package wangjg.commons.character;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author wangjg
 *
 */
public class DigestUtil {

	private static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	/**
	 * 用MD5摘要算法加密字符串
	 * @param String 要加密的字符串
	 * @return String 加密好的字符串
	 */
	public static String md5(String piStr) {
		String encodeStr = "";
		try {
			java.security.MessageDigest alg = java.security.MessageDigest.getInstance("MD5");
			alg.update(piStr.getBytes());
			byte[] digesta = alg.digest();
			encodeStr = byte2hex(digesta);
		} catch (Exception e) {
		}
		return encodeStr;
	}
	/**
	 * 将摘要信息转换为相应的编码
	 * @param code 编码类型
	 * @param message 摘要信息
	 * @return 相应的编码字符串
	 */
	public static String SHA1(String message) {
		java.security.MessageDigest md;
		String encode = null;
		try {
			md = java.security.MessageDigest.getInstance("SHA-1");
			encode = byte2hex(md.digest(message.getBytes()));
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return encode;
	}

	/**
	 * 将摘要信息转换为相应的编码
	 * @param code 编码类型
	 * @param message 摘要信息
	 * @return 相应的编码字符串
	 */
	public static String SHA256(String message) {
		java.security.MessageDigest md;
		String encode = null;
		try {
			md = java.security.MessageDigest.getInstance("SHA-256");
			encode = byte2hex(md.digest(message.getBytes()));
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return encode;
	}

	public static String getFileHash(String fileName) throws Exception {
		InputStream fis = null;
		try {
			fis = new FileInputStream(fileName);
			return getFileHash(fis);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(fis!=null){
				fis.close();
			}
		}
		return null;
	}
	
	public static String getFileHash(InputStream fis) throws IOException  {
		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		byte[] buf = new byte[1024];
		int count = 0;
		while((count=fis.read(buf))!=-1){
			messageDigest.update(buf, 0, count);
		}
		String str = byte2hex(messageDigest.digest());
		return str;
	}
	
	private static String byte2hex(byte[] buf) {
		StringBuilder sb = new StringBuilder(buf.length * 2);
		for (int i = 0; i < buf.length; i++) {
			sb.append(hexChar[(buf[i] & 0xf0) >>> 4]);
			sb.append(hexChar[buf[i] & 0x0f]);
		}
		return sb.toString();
	}
	
	public static void main(String args[]) throws Exception{
		long t = System.currentTimeMillis();
		System.out.println(getFileHash("D:\\TDDOWNLOAD\\eclipse-indigo-x86.rar"));
		System.out.println(System.currentTimeMillis()-t);
	}
}
